//
//  WBPublishViewController.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/12.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//发布微博可见权限
enum userAuthorityType: Int {
    
    case Recent = 0 //默认
    case Default = 1 //仅自己可见
    case sidekick = 2   //密友可见
    case group = 3     //指定分组可见
    
}

let placeholder = "在此输入您要分享的内容.."

class WBPublishViewController: UIViewController,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    //控制器消失让键盘消失
    override func viewWillDisappear(animated: Bool) {
        textView.resignFirstResponder()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = RandomColor()
        setupNav()
        setupTextView()
        setupTooBar()
        ///键盘即将弹出来通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //点击表情
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "showEmoticon:", name:kNotificationEmoticonTransform, object: nil)
        /// 删除表情的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteEmoticon:", name: deleButtonNotificationCilck, object:nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - Navigation
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        navigationItem.rightBarButtonItem?.enabled = true
        let label = UILabel(frame: CGRectMake(0, 0, 200, 44))
        let str = "发布微博\n正在输入内容"
        label.numberOfLines = 0
        
        label.textAlignment = .Center
        //可变的
        let attributer = NSMutableAttributedString(string: str)
        
        //添加属性
        attributer.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13),NSForegroundColorAttributeName:UIColor.redColor()], range: NSMakeRange(0,str.characters.count))
        
        attributer.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16),NSForegroundColorAttributeName:UIColor.blackColor()], range: NSMakeRange(0, str.characters.count - 6))
        
        label.attributedText = attributer
        navigationItem.titleView = label
        
    }
    
    
    //MARK: - textView布局
    func setupTextView() {
        
        view.addSubview(textView)
        textView.font = UIFont.systemFontOfSize(12)
        textView.holdString = placeholder
        textView.delegate = self
        //添加colltionView视图
        textView.addSubview(chooseView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.top.equalTo(view.snp_top)
            make.bottom.equalTo(view.snp_bottom)
            make.right.equalTo(view.snp_right)
            //            make.edges.equalTo(view.snp_edges)
            
        }
        //通知 让键盘退出
        textView.keyboardDismissMode = .OnDrag
        //拖拽方向
        textView.alwaysBounceVertical = true
        
        chooseView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(8)
            make.top.equalTo(textView.snp_top).offset(100)
            make.width.equalTo(WBUIScreenW - 2*8)
            make.height.equalTo(chooseView.snp_width)
        }
    }
    
    
    //MARK: - 点击返回
    @objc private func dismiss() {
        
        //注销键盘的第一响应者
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    //MARK: - 发布点击方法
    @objc private func publish(){
       //判断是否是发布图片微博
        if chooseView.getIamges().count > 0 {
          updateImage()
        }else {
        updateWeibo() //发布一条文字微博
        
        }
    }
    
    //MARK: - 发布图片微博
    private func updateImage() {
        
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //需要以表单的形式上传
        let afn = AFHTTPSessionManager()
        
        guard let token = WBOauthViewModel.shareInstance.access_token else {
            SVProgressHUD .showErrorWithStatus("没有登录")
            return
        }
        //需要以POST方式上传
        /*
        visible	false	int	微博的可见性，0：所有人能看，1：仅自己可见，2：密友可见，3：指定分组可见，默认为0。
        access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
        status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
        pic	true	binary	要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。
        */
        
        let pramer = [
            "status": textView.getPublishText(),
            "access_token": token
        ]
        
        //1.需要把图片压缩
        let image = chooseView.getIamges().first
        //需要把图片转换成 NSDate
        //压缩比
        let date = UIImageJPEGRepresentation(image!, 0.5)
        
        afn.POST(url, parameters: pramer, constructingBodyWithBlock: { (from) -> Void in
            from.appendPartWithFileData(date!, name: "pic", fileName: "test", mimeType: "JPEG/GIF/PNG")
            
            }, progress: nil, success: { (_, JSON) -> Void in
                SVProgressHUD .showInfoWithStatus("图片上传成功")

            }) { (_ , error) -> Void in
                
                SVProgressHUD .showErrorWithStatus("上传失败!")
                return
           }
       }
    
    
    
    //MARK: - 文字微博
    private  func updateWeibo() {
        
        let url = "https://api.weibo.com/2/statuses/update.json"
        
        guard let token = WBOauthViewModel.shareInstance.access_token else {
            //          fatalError("你没有登录")
            //
            return
        }
        
        /*
        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
        status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
        */
        
        let paramgers = ["access_token": token,
            "status":textView.getPublishText()
            
        ]
        
        WBHTTPClient.shareInstance.request(.POST, URLString: url, parameters: paramgers, success: { (_ , JSON) -> Void in
            SVProgressHUD .showInfoWithStatus("发布成功")
            
            self.textView.text = ""//清空输入的内容
            
            }) { (_ , error) -> Void in
                
                SVProgressHUD .showErrorWithStatus("发布失败\(error.description)")
        
                 SVProgressHUD .show()
                 return
            }
        }
    
    private func  setupTooBar() {
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
        }
        //添加按钮
        var items:[UIBarButtonItem] = [UIBarButtonItem]()
        //用循环来创建 把方法保存在字典中
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        for itemSetting in itemSettings {
            let imageName = itemSetting["imageName"]!
            //给按钮添加点击方法
            let action = itemSetting["action"]
            let item = UIBarButtonItem(imageName: imageName, action: action, target: self)
            //添加到数组里
            items.append(item)
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //移除最后一个弹簧
        items.removeLast()
        toolBar.items = items
    }
    
    //    MARK:- 打开相册方法
    @objc  private func choosePicture() {
        let pic = UIImagePickerController()
        pic.delegate = self
        //判断相机是否可用
        if UIImagePickerController.isSourceTypeAvailable(.Camera){
            /*
            case PhotoLibrary -- 所有的相册
            case Camera         -- 相机，要用相机之前，先检测一下 相机是否可用
            case SavedPhotosAlbum -- 保存的图片相册
            */
            pic.sourceType = .Camera
            //进行跳转
            presentViewController(pic, animated: true, completion: { () -> Void in
                
            })
        }
        pic.sourceType = .PhotoLibrary
        
        presentViewController(pic, animated: true) { () -> Void in
            
        }
    }
    
    //   MARK: - 显示表情方法
    @objc  private func inputEmoticon() {
        
        // print(textView.inputView)
        //      textView.inputView = emotionView
        
        textView.inputView == nil ? (textView.inputView = emotionView): (textView.inputView = nil)
        //重新加载
        textView.reloadInputViews()
        
        textView.becomeFirstResponder()
    }
    
    //MARK: -   改变键盘frame通知方法
    @objc private func changeToolBarFrame(noti:NSNotification) {
        
        // print(noti.userInfo)
        /*
        Optional([UIKeyboardFrameBeginUserInfoKey
        NSRect: {{0, 667}, {375, 258}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 538},
        UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 409}, {375, 258}}, UIKeyboardAnimationDurationUserInfoKey: 0.25, UIKeyboardCenterBeginUserInfoKey: NSPoint: {187.5, 796}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1])
        */
        
        if  let rect = noti.userInfo?[UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        {
            if rect.origin.y == (WBUIScreenH - rect.size.height){
                
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    make.bottom.equalTo(self.view.snp_bottom).offset(-rect.size.height)
                })
            }else if rect.origin.y == WBUIScreenH {
                
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    make.bottom.equalTo(self.view.snp_bottom)
                })
            }
            
            //动画随着键盘改变
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.toolBar.layoutIfNeeded() //动画约束
            })
        }
    }
    
    //点击表情通知调用的方法
    @objc private func showEmoticon(noti:NSNotification){
        
        if let emticon = noti.userInfo?["key"] as? WBEmoticon {
            //显示表情的方法在textView中封装
            textView.insertEmoticon(emticon)
        }
    }
    
    deinit {
        print("控制器释放了")
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    //    MARK:- 点击表情删除按钮的通知
    @objc private func deleteEmoticon(noti:NSNotification) {
        textView.deleteBackward() //删除表情
    }
    //MARK:- 懒加载
    //ToolBar
    lazy var toolBar:UIToolbar = UIToolbar()
    //选择 图片视图
    lazy var chooseView: WBChooseView = {
        let choose = WBChooseView()
        
        //避免循环引用使用 weak
        weak var weakSelf = self
        
        choose.closure = {
            //print("闭包回调用相册")
            weakSelf?.choosePicture()
        }
        return choose
    }()
    
    
    //发布textView
    lazy var textView: WBTextView = WBTextView()
    
    //表情控制器
    lazy var emotionView: WBEmoticonView = {
        let emotion = WBEmoticonView()
        
        //设置frame
        emotion.frame = CGRectMake(0,0,WBUIScreenW,216)
        
        return emotion
    }()
    
}




extension WBPublishViewController {
    //键盘值改变
    func textViewDidChange(textView: UITextView) {
        if textView.hasText(){
            self.textView.holdString = "" //输入有值就显示为空
        }else {
            self.textView.holdString = placeholder
        }
        //重绘
        self.textView.setNeedsDisplay()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

// MARK: - 相册的代理方法
extension WBPublishViewController {
    
    //iOS已经废弃了 能够直接返回图片 实现了此方法 就不会走下面的返回图片方法了
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        chooseView.addImage(image)
        picker.dismissViewControllerAnimated(false) { () -> Void in
            
        }
    }
    //    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    //
    //    }
    
    //点击取消之后触发
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
        picker.dismissViewControllerAnimated(false) { () -> Void in
            
        }
    }
}
